package tomcat;

import standard.HelloServlet;
import standard.HttpServlet;
import standard.HttpServletRequest;
import standard.HttpServletResponse;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class Task implements Runnable {
    private final Socket socket;

    public Task(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {

        try (InputStream is = socket.getInputStream()) {
            /**
             * 1.读取客户端发来的数据，
             * 并按照HTTP协议的请求格式进行解析，
             * 最终封装成一个HttpServletRequest对象
             */
            HttpServletRequest req = HttpServletRequestImpl.parse(is);

            //2.构建一个空的HttpServletResponse对象
            OutputStream os = socket.getOutputStream();
            HttpServletResponse resp = HttpServletResponseImpl.build(os);

            //3.根据规则，选择合适的HttpServlet 对req进行处理
            HttpServlet servlet = selectServlet(req);

            //4.调用Servlet的process方法，进行业务处理
             servlet.process(req,resp);     //每次有请求过来，都会调用一次process方法

            //5.resp对象已经被业务填充了正确的数据(响应行/响应头/响应体)
            //  按照HTTP协议响应格式，构建响应数据并发送
            ((HttpServletResponseImpl)resp).send();

            //6.HTTP/1.0 协议，短连接方式处理—— 关闭socket
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private HttpServlet servlet = new HelloServlet();

    private HttpServlet selectServlet(HttpServletRequest req) {
        return servlet;
    }
}
